package com.aigou.admin.controller;

import com.aigou.admin.annotation.ResponseResult;
import com.aigou.admin.utils.Md5Util;
import com.aigou.admin.utils.UUIDUtils;
import com.aigou.admin.entity.PageEntity;
import com.aigou.admin.entity.User;
import com.aigou.admin.service.UserService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @Author: Hor
 * @Date: 2024/12/2 18:46
 * @Version: 1.0
 */
@RestController
@RequestMapping("/user")
@AllArgsConstructor
@ResponseResult
public class UserController {

    private final UserService userService;

    @RequestMapping("/save")
    public Boolean save(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String name = req.getParameter("user_name");
        String pwd = req.getParameter("user_pwd");
        Integer type = Integer.valueOf(req.getParameter("user_type"));
        // 将密码加密
        String md5Pwd = Md5Util.getMD5String(pwd);

        // 生成uuid
        String uuid = UUIDUtils.generateUUIDWithoutHyphens();

        return userService.save(new User(uuid, name, md5Pwd, type));
    }

    @RequestMapping("/update")
    public Boolean update(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String id = req.getParameter("user_id");
        String name = req.getParameter("user_name");
        String pwd = req.getParameter("user_pwd");

        // 将密码加密
        String md5Pwd = Md5Util.getMD5String(pwd);

        Integer type = Integer.valueOf(req.getParameter("user_type"));
        return userService.update(new User(id, name, md5Pwd, type));
    }

    @RequestMapping("/delete")
    public Boolean delete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String userId = req.getParameter("user_id");
        return userService.remove(userId);
    }

    @RequestMapping("/findById")
    public User findById(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //获得用户id
        String userId = req.getParameter("user_id");
        //查询用户
        return userService.findById(userId);
    }

    @RequestMapping("/findAll")
    public List<User> findAll(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //查询用户
        //转换为JSON,通过流发送给客户端
        return userService.findAll();
    }

    @RequestMapping("/page")
    public PageEntity<User> page(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String currentPage = req.getParameter("currentPage");
        String pageSize = req.getParameter("pageSize");
        String userName = req.getParameter("user_name");
        //查询用户
        return userService.findUsersByPage(Integer.parseInt(currentPage), Integer.parseInt(pageSize),userName);

    }


}
